#include "httpmgr.h"
#include <QByteArray>



void HttpMgr::PostHttpReq(QUrl url, QJsonObject json, ReqId req_id, Modules mod)
{
    //将QJsonObject对象转化为字节序
    QByteArray data = QJsonDocument(json).toJson();

    QNetworkRequest request(url);

    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(data.length()));
    //请求方法 路径 http版本号， 首部字段 ， 请求体
    QNetworkReply* reply = _manager.post(request,data);

    auto self(shared_from_this());
    //异步的设置信号槽，等发送完成之后执行
    QObject::connect(reply, &QNetworkReply::finished, this, [reply,self,req_id,mod](){

        if(reply->error()!=QNetworkReply::NoError)
        {
            qDebug()<<"post http 请求错误："<<reply->errorString()<<"\n";

            emit self->sig_http_finish(req_id,"",ErrorCodes::ERR_NETWORK,mod);
            reply->deleteLater();
            return;
        }
        QByteArray responseData = reply->readAll();
#if 1
        //发送信号通知完成
        emit self->sig_http_finish(req_id,responseData,ErrorCodes::SUCCESS,mod);
        reply->deleteLater();
        return;
#endif

    });




}



void HttpMgr::slot_http_finish(ReqId req_id, QString res, ErrorCodes err, Modules mod)
{
    if(mod==Modules::REGISTERMOD)
    {
        emit sig_reg_mod_finish(req_id,res,err);
    }
    else if(mod==Modules::RESETMOD)
    {
        emit sig_reset_mod_finish(req_id,res,err);
    }
}



HttpMgr::HttpMgr()
{
    QObject::connect(this,&HttpMgr::sig_http_finish,this,&HttpMgr::slot_http_finish);

}

